using System;
using System.Collections.Generic;
using System.Text;
using LibGreen.Jabber.ProtocolElements;
using LibGreen.Jabber.Connection;

namespace LibGreen.Jabber.Dispatchers
{
    /// <summary>
    /// Processes and dispatches presence stanzas
    /// </summary>
    class PresenceDispatcher : IDispatcher
    {
        private readonly XmppConnection parentConnection;
        private readonly Session parentSession;

        /// <summary>
        /// Initializes a new <see cref="PresenceDispatcher"/>
        /// </summary>
        /// <param name="parentConnection">The <see cref="XmppConnection"/> that sends elements to this dispatcher</param>
        public PresenceDispatcher(XmppConnection parentConnection)
        {
            this.parentConnection = parentConnection;
            this.parentSession = parentConnection.Parent;
        }

        #region IDispatcher Members
        /// <summary>
        /// Initializes the dispatcher
        /// </summary>
        public void Initialize()
        {
        }

        /// <summary>
        /// Dispatches a newly received <see cref="Element"/> for processing
        /// </summary>
        /// <param name="element">The newly received <see cref="Element"/> that must be processed</param>
        /// <returns><c>true</c> if the dispatcher processed the element, <c>false</c> otherwise</returns>
        public bool DispatchElement(Element element)
        {
            if (element.Name == "presence")
            {
                ProcessPresenceElement(new PresenceElement(element));
                return true;
            }
            return false;
        }
        #endregion

        /// <summary>
        /// Processes a <see cref="PresenceElement"/>
        /// </summary>
        /// <param name="presenceElement">The &lt;presence&gt; element to process</param>
        private void ProcessPresenceElement(PresenceElement presenceElement)
        {
            switch (presenceElement.Type)
            {
                case PresenceElementType.Unavailable:
                case PresenceElementType.None:
                    parentSession.Presence.OnContactStatusChange(presenceElement);
                    break;
                case PresenceElementType.Subscribe:
                    parentSession.Presence.OnSubscriptionRequested(new Jid(presenceElement.From));
                    break;
            }
        }
    }
}
